<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" customClass="customWidth" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px" label-position="left">
			<el-row :gutter="24">
				<el-col :lg="24">
					<el-form-item label="企业名称" prop="enterprise_id">
						<el-input v-model="form.enterprise_id" placeholder="企业名称"  clearable maxlength="40"></el-input>
						
					</el-form-item>
				</el-col>
				<el-col :lg="24">
					<el-form-item label="入驻楼宇" prop="room">
						<el-cascader
							:disabled="buildingDisabled"
							v-model="form.building_id"
							:options="buildingList"
							:props="{ expandTrigger: 'hover', value: 'id', label: 'name', children: 'buildingData'}"
							@change="handleChangeBuilding"></el-cascader>
					</el-form-item>
				</el-col>
				<el-col :lg="24">
					<el-form-item label="入驻空间" prop="room">
						<el-cascader
						    ref = "roomRef"
							v-model="form.space_id"
							:options="roomList"
							:props="{ expandTrigger: 'hover', value: 'id', label: 'room', children: 'spaceData'}"
							@change="handleChange"></el-cascader>
					</el-form-item>
				</el-col>
				<el-col :lg="24">
					<el-form-item label="租用面积" prop="room_size">
						<el-input v-model="form.room_size" placeholder="租用面积" disabled clearable maxlength="40"></el-input>
					</el-form-item>
				</el-col>
				<el-col :lg="12">
					<el-form-item label="入驻时间" prop="checkin_date">
						<el-date-picker v-model="form.checkin_date" placeholder="入驻时间" type="date" value-format="YYYY-MM-DD" style="width: 100%;"></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :lg="12">
					<el-form-item label="有效期至" prop="valid_date">
						<el-date-picker v-model="form.valid_date" placeholder="有效期至" type="date" value-format="YYYY-MM-DD" style="width: 100%;"></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :lg="24">
					<el-form-item label="联系人" prop="contacts">
						<el-input v-model="form.contacts" placeholder="联系人" clearable maxlength="40"></el-input>
					</el-form-item>
				</el-col>
				<el-col :lg="24">
					<el-form-item label="联系方式" prop="tel">
						<el-input v-model="form.tel" placeholder="联系方式" clearable maxlength="40" @change="getFloorList"></el-input>
					</el-form-item>
				</el-col>
				<el-col :lg="24">
					<el-form-item label="客户经理" prop="account_manager">
						<select-user-dialog v-model:accountId="form.account_manager" style="margin-left:-10px;" :mode="true"/>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">确 定</el-button>
		</template>
	</el-dialog>

</template>
<script>
import selectUserDialog from "@/views/module/selectUserDialog";
import selectDeptDialog from "@/views/module/selectDeptDialog";
import selectUserLevelDialog from "@/views/module/selectUserLevelDialog";
import {defineAsyncComponent} from "vue";
import msgBoxCheckBox from "@/views/module/msgBoxCheckBox";
import AttachMenu from '@/views/module/attachMenu'
const scEditor = defineAsyncComponent(() => import('@/components/scEditor'));
export default {
	emits: ['success', 'closed'],
	components: {
		selectUserLevelDialog,
		msgBoxCheckBox,
		selectUserDialog,
		selectDeptDialog,
		AttachMenu,
		scEditor
	},
	data() {
		return {
			visible: false,
			isSaveing: false,
			isShowMsg: false,
			floorList:[],
			epList:[],
			roomList:[],
			deviceList:[],
			mode: "add",
			titleMap: {
				add: '新增入驻',
				edit: '编辑入驻',
				show: '查看入驻'
			},
			fileList: [],
			apiObj: this.$API.file.attach.uploadFile,
			templates: [],
			form2: {},
			form: {
				meetingId: '',
				dbcode: '',
				package_id: '',
				park_id: '',
				building_id: '',
				enterprise_id: '',
				roomId: '',
				deviceId: [],
				checkin_date: '',
				valid_date: '',
				userJoin: '',
				deptJoin: '',
				levelJoin: '',
				otherJoin: '',
				content: '',
				msgType: '',
				attachId: '',
				checkin_id: '',
				checkin_status: '1',
				space_id:[],
			},
			formSpace:{},
			formPackage:{},
			formPS:{},
			rules: {
				dbcode: [
					{required: true, message: '入园编号不能为空', trigger: 'blur'}
				]
			},
			area_id: '',
			buildingList:[],
			buildingDisabled:false
		}
	},

	methods: {
		handleChange(e){
			this.form.room_size = this.roomList.filter(x=>{return x.id == e[0]})[0].spaceData.filter(y=>{return y.id==e[1]})[0].room_size
		},
		publishDateAfter(time){
			return time.getTime()<(Date.now()-24*60*60*1000)
		},
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		submit() {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					this.form.deviceId = this.form.deviceId.join(",");
					var res;
					if (this.mode == "add") {
						// // 添加空间（名称及面积）
						// this.formSpace.building_id = 12
						// this.formSpace.category = 4
						// const resSpace = await this.$API.attractinvestment.space.insertSpace.post(this.formSpace);
						// // 添加包（包名）
						// this.formPackage = {name:this.formSpace.room}
						// const resPackage = await this.$API.attractinvestment.package.insertPackage.post(this.formPackage);
						// // 添加关联（关联上述二者）
						// this.formPS = {
						// 	package_id: resPackage.data,
						// 	space_id: resSpace.data,
						// 	floor_id: this.formSpace.floor_id,
						// 	building_id: 12
						// }
						// const resPS = await this.$API.attractinvestment.ps.insertPS.post(this.formPS);
						// // 添加话术
						// this.form.package_id = resPackage.data
						// this.form.building_id = 12
						// this.form.space_id = resSpace.data
						this.form.space_id = this.form.space_id[1]
						delete this.form.room_size
						res = await this.$API.operation.checkin.insertCheckin.post(this.form);
						await this.$API.attractinvestment.space.updateSpace.post({id:this.form.space_id,category:4});
						// res = await this.$API.operation.checkin.newCheckin.post(this.form);
					} else if (this.mode == "edit") {
						this.form.space_id = this.form.space_id[1]
						delete this.form.room_size
						res = await this.$API.operation.checkin.updateCheckin.post(this.form);
					}
					this.isSaveing = false;
					if (res.code == 200) {
						const selectedNodes = this.$refs.roomRef.getCheckedNodes();
                        console.log('选中的名称11:',selectedNodes[0].pathLabels);
						this.$emit('success',selectedNodes[0].pathLabels[1])
						this.visible = false;
						this.$message.success("操作成功")
						this.form =  {
										meetingId: '',
										dbcode: '',
										package_id: '',
										park_id: '',
										building_id: '',
										enterprise_id: '',
										roomId: '',
										deviceId: [],
										checkin_date: '',
										valid_date: '',
										userJoin: '',
										deptJoin: '',
										levelJoin: '',
										otherJoin: '',
										content: '',
										checkin_status: '1',
										msgType: '',
										attachId: '',
										checkin_id: ''
									}
					} else {
						this.$alert(res.message, "提示", {type: 'error'})
					}
				}
			})
		},
		async getFloorList()
		{
			var res = await this.$API.attractinvestment.floor.getFloorList.get({'building_id': this.form.building_id});
			if (res.code == 200) {
				this.floorList = res.data.list;
			}
		},
		
		async getCanUseDeviceList()
		{
			var res = await this.$API.office.meeting.getCanUseDeviceList.get();
			if (res.code == 200) {
				this.deviceList = res.data;
			}
		},
		setCreateData(data,paramRoomList)
		{
			this.roomList = []
			this.form.building_id = data.building_id;
			this.roomList = paramRoomList;
			this.roomList.forEach(element => {
				element.room = element.name
				element.spaceData =  element.spaceData.filter(space => space.category != 4)
			});
			
			this.form.roomId = data.roomId;
			this.form.checkin_date = data.checkin_date;
			this.form.valid_date = data.valid_date;
			this.form.space_id = data.space_id;
		},
		setData(data,roomList) {
			this.roomList = roomList;
				this.roomList.forEach(element => {
				element.room = element.name
			});
			this.form.building_id = data.building_id;
			this.form.checkin_id = data.checkin_id;
			this.form.roomId = data.roomId;
			this.form.checkin_date = data.checkin_date;
			if(data.valid_date){
				this.form.valid_date = data.valid_date+"T00:00:00";
			}
			this.form.enterprise_id = data.enterprise_id;
			this.form.account_manager = data.account_manager;
			this.form.contacts = data.contacts;
			this.form.tel = data.tel;

		},
		setData(data) {
			this.createBuildingList()
			this.createRoomList(data.building_id, data.space_id);
			//this.createRoomList(data.building_space_id, data.space_id);
			this.form.building_id = data.building_id;
			this.form.checkin_id = data.checkin_id;
			this.form.roomId = data.roomId;
			this.form.space_id = [data.building_code.toString(), parseInt(data.space_id)]
			this.form.checkin_date = data.checkin_date;
			if(data.valid_date){
				this.form.valid_date = data.valid_date+"T00:00:00";
			}
			this.form.enterprise_id = data.enterprise_id;
			this.form.account_manager = data.account_manager;
			this.form.contacts = data.contacts;
			this.form.tel = data.tel;
			this.form.room_size = data.room_size
		},
		addNewFile(res, file)
		{
			let tArr = this.form.attachId.split(",");
			tArr.push(res.data.attachId);
			this.form.attachId = tArr.join(",");
		},

		async createRoomList(building_id, space_id) {
			let buildingIdParam;
			if(this.mode == 'edit'){//修改
			  buildingIdParam = building_id;
			} else {//新增
				if(!this.form.building_id) {
					buildingIdParam = '';
				}else {
					buildingIdParam = this.form.building_id
				}
			}
			let allData = await this.$API.attractinvestment.building.getFloorSpaceByBuildingId.get({ building_id: buildingIdParam });
				if(allData.code == 200) {
					this.roomList = [];
					for (let i = 0; i < allData.data.length; i++) {
					this.roomList.push({
						id: allData.data[i].id,
						room: allData.data[i].floor + '层',
						spaceData: allData.data[i].spaceList.filter(space => space.category != 4 || space.id == space_id),
					});
				}
			}
		},
		async createRoomListForSpacePlan(buildingId) {
			    this.createBuildingList()
				this.buildingDisabled = true
			    this.form.building_id = buildingId
				let allData = await this.$API.attractinvestment.building.getFloorSpaceByBuildingId.get({ building_id: buildingId });
				if(allData.code == 200) {
					this.roomList = [];
					for (let i = 0; i < allData.data.length; i++) {
					this.roomList.push({
						id: allData.data[i].id,
						room: allData.data[i].floor + '层',
						spaceData: allData.data[i].spaceList.filter(space => space.category != 4),
					});
				}
			}
		},

		handleChangeBuilding(e){
			 this.form.building_id = e[0];
			 this.$nextTick(() => {
				 this.createRoomList(e[0])
			 })
		},
		async createBuildingList() {
			if(!this.area_id){
				this.area_id = '总部基地'
			}
	
			let allData = await this.$API.attractinvestment.building_new.getBuildingByAreaId.get({ area_id: this.area_id });
			console.log(this.area_id)
			if(allData.code == 200) {
				this.buildingList = [];
				for (let i = 0; i < allData.data.length; i++) {
					this.buildingList.push({
						id: allData.data[i].building_id,
						name: allData.data[i].name
					});
				}
			}
		}
	}
}
</script>

<style>
.customWidth {
	width: 60%;
}
</style>
